package com.demo.order.web;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.demo.order.pojo.Order;
import com.demo.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderController {

   @Autowired
   private OrderService orderService;

    @SentinelResource(value = "getInfo", blockHandler = "blockHandler", fallback = "fallback" )
    @GetMapping("{id}")
    public Order getInfo(@PathVariable("id") Long id) {
        // 根据id查询订单并返回
        // 模拟异常熔断
        int flag = 10 / 0;
        return orderService.getInfo(id);
    }

    /**
     * 限流触发的方法
     * 注意：限流返回值必须与接口返回值类型一致，参数必须与接口传参方法一致
     */
    public Order blockHandler(@PathVariable("id") Long id, BlockException e) {
        System.out.println(e);
        return new Order().setAddress("哈哈哈，你订单点太快了,被限流了吧！！！");
    }
    /**
     * 熔断触发的方法
     * 注意：熔断返回值必须与接口返回值类型一致，参数必须与接口传参方法一致
     */
    public Order fallback(@PathVariable("id") Long id) {
        return new Order().setAddress("哈哈哈，这是一个订单熔断降级方法哦！！！");
    }

    @GetMapping("/list")
    public List<Order> list() {
        return orderService.list();
    }

    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody Order order) {
        Map<String, Object> response = new HashMap<>();
        if (orderService.save(order)) {
            response.put("code", 200);
            response.put("msg", "添加成功");
        } else {
            response.put("code", 500);
            response.put("msg", "添加失败");
        }
        return response;
    }

    @PutMapping("/update")
    public Map<String, Object> edit(@RequestBody Order order) {
        Map<String, Object> response = new HashMap<>();
        if (orderService.updateById(order)) {
            response.put("code", 200);
            response.put("msg", "修改成功");
        } else {
            response.put("code", 500);
            response.put("msg", "修改失败");
        }
        return response;
    }

    @DeleteMapping("/{id}")
    public Map<String, Object>  remove(@PathVariable("id") Long id) {
        Map<String, Object> response = new HashMap<>();
        if (orderService.removeById(id)) {
            response.put("code", 200);
            response.put("msg", "删除成功");
        } else {
            response.put("code", 500);
            response.put("msg", "删除失败");
        }
        return response;
    }
}
